package com.z.system.repository;

import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import com.z.system.model.Permission;

/**
 * 权限仓库接口，提供权限数据访问方法
 */
@Repository
public interface PermissionRepository extends JpaRepository<Permission, UUID> {

    /**
     * 根据权限标识查找权限
     */
    Permission findByPermission(String permission);

    /**
     * 根据角色ID查找权限
     */
    @Query(value = "SELECT p.* FROM t_permission p JOIN t_role_permission rp ON p.id = rp.permission_id WHERE rp.role_id = :roleId", nativeQuery = true)
    List<Permission> findByRoleId(UUID roleId);

    /**
     * 根据角色ID集合查找权限（自动去重）
     */
    @Query(value = "SELECT DISTINCT p.* FROM t_permission p JOIN t_role_permission rp ON p.id = rp.permission_id WHERE rp.role_id IN :roleIds", nativeQuery = true)
    List<Permission> findMenusByRoleIds(Set<UUID> roleIds);

    /**
     * 根据权限ID集合查找权限
     */
    List<Permission> findByIdIn(Set<UUID> ids);

    /**
     * 检查权限标识是否已存在
     */
    boolean existsByPermission(String permission);

    /**
     * 根据父权限ID和角色ID集合查找按钮权限
     * 用于查询指定页面下的按钮权限
     */
    @Query(value = "SELECT p.* FROM t_permission p JOIN t_role_permission rp ON p.id = rp.permission_id WHERE p.parent_id = :parentId AND p.type = 2 AND rp.role_id IN :roleIds ORDER BY p.sort ASC", nativeQuery = true)
    List<Permission> findButtonPermissionsByParentIdAndRoleIds(UUID parentId, Set<UUID> roleIds);
}